import type {ResponseData, ResponsePaginationData} from '@/utils/request';
import {SUCCESS_CODE} from '@/utils/request';
import type {RequestData} from '@ant-design/pro-table';
import type {
  AuthPermission,
  AuthRoleAddItem,
  AuthRoleEditItem,
  AuthRoleQueryListParams,
  AuthRoleTableListItem,
  DetailItem
} from './data';
import {request} from 'umi';

type Pagination = { page?: number; pageSize?: number };

export interface AdminRoleListItem {
  id: any;
  name: string;
  accesses?: { id: string; name: string }[];
}

/**
 * 获取账号角色列表
 * @param params
 */
export async function queryAdminRoleList(
    params: Pagination & AuthRoleQueryListParams,
): Promise<RequestData<AuthRoleTableListItem>> {
  const {page = 1, pageSize = 20, name} = params;
  const res = await request<ResponsePaginationData<AdminRoleListItem>>('/sys/role/list', {
    params: {page, pageSize, name},
  });
  return {
    success: true,
    total: res.data.total,
    data: res.data.list,
  };
}

export async function queryUserAdminRolesList(params: {
  userId: string;
}): Promise<RequestData<AuthRoleTableListItem>> {
  if (!params.userId) {
    return {
      success: false,
      total: 0,
      data: [],
    };
  }
  const res: ResponsePaginationData<{
    id: string;
    name: string;
    code: string;
  }> = await request(`/sys/admin/${params.userId}/roles`, {method: 'GET'});
  return {
    success: res.code === SUCCESS_CODE,
    total: res.data.total,
    data: res.data.list || [],
  };
}

export async function queryAdminRoleDetail(params: {
  id: string;
}): Promise<{ success: boolean; data?: DetailItem }> {
  const res: ResponseData<DetailItem> = await request(`/sys/role/${params.id}`);

  if (res?.code !== SUCCESS_CODE) {
    return {success: false};
  }

  return {
    success: true,
    data: {
      id: res.data.id,
      name: res.data.name,
      permissions: res.data.permissions,
    },
  };
}

/**
 * 创建一个账号角色
 * @param params
 */
export async function addAdminRole(params: AuthRoleAddItem) {
  return request('/sys/role/create', {
    method: 'POST',
    data: {name: params.name, permission_ids: params.permissions?.map(o => o.id)},
  });
}

export async function editAdminRole(params: AuthRoleEditItem) {
  const {id, name} = params;
  return request(`/sys/role/${id}`, {method: 'POST', data: {name}});
}

export interface AdminRoleAccessesUpdate {
  roleId: string;
  permissions: AuthPermission[];
}

/**
 * 更新用户角色中的权限配置信息
 *
 * @param params
 */
export async function updateAdminRoleAccesses(
    params: AdminRoleAccessesUpdate,
): Promise<ResponseData<boolean>> {
  const {roleId, permissions} = params;
  const accessIds = permissions?.map(acc => acc.id);
  return request(`/sys/role/${roleId}/permissions`, {data: {accessIds}, method: 'POST'});
}

/**
 * 获取所有可配置权限
 * @param params
 */
export async function fetchConfigurableAuthPermission(
    params: {
      adminId?: string;
    } & Pagination,
): Promise<RequestData<AuthPermission>> {
  const {adminId, page = 1, pageSize = 10000} = params;

  const res: ResponsePaginationData<AuthPermission> = await request(`/sys/permission/list`, {
    params: {
      adminId,
      page,
      pageSize,
    },
  });

  return {
    total: res.data.total,
    success: res.code === SUCCESS_CODE,
    data: res.data.list || [],
  };
}

/**
 * 获取某一个角色下的权限列表
 *
 * @param params
 */
export async function queryAdminRoleAccessList(params: {
  roleId: string;
}): Promise<ResponseData<AuthPermission[]>> {
  console.assert(params.roleId, 'roleId is required');
  const res: ResponseData<AuthPermission[]> = await request(`/sys/role/${params.roleId}/permissions`);

  return {
    code: SUCCESS_CODE,
    message: res.message || "没有数据",
    data: res.data || [],
  };
}

export async function removeAdminRole(params: { id: string }): Promise<void> {
  const res: ResponseData<any> = await request(`/sys/role/${params.id}`, {method: 'DELETE'});
  if (res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
}
